<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>基于Promise处理Ajax请求</title>
	</head>
	<body>

		<script>
			/* 
			  基于Promise处理Ajax请求--处理原生Ajax 
			 */
			function queryData(url) {
				var p = new Promise(function(resolve, reject) {
					var xhr = new XMLHttpRequest();
					xhr.onreadystatechange = function() {
						if (xhr.readyState != 4) {
							return;
						}
						if (xhr.readyState == 4 && xhr.status == 200) {
							resolve(xhr.responseText);
						} else {
							reject("服务器出错！");
						}

					}
					xhr.open("get", url);
					xhr.send(null);
				});
				return p;
			}

			/* queryData("test.txt").then(function(data){
				console.log(data);
			},function(info){
				console.log(info);
			}); */

			//=====================================
			//发送多个Ajax请求,并且保证顺序
			queryData("test.txt").then(function(data) {
				console.log(data);
				return queryData("test1.txt");//return新的Promise对象
			}).then(function(data) {
				console.log(data);
				return queryData("test2.txt");
			}).then(function(data) {
				console.log(data);
			});
		</script>
	</body>
</html>
